from lib import *
from demo import *
from row import *
from rrsl import *
from random import shuffle

@eg
def rrsl1():
  def myshow(leafp,n,pre,lst) :
    if leafp:
      for one in lst: print '   '*n,one
  Row.id=0
  rrsl(Table().slurp('data/test4.csv')).show(extra=myshow)

@eg
def rrsl2():
   import cProfile
   cProfile.run('rrsl(Table().slurp("data/autompg25K.csv"))')

@eg
def rrsl3():
  rrsl(Table().slurp("data/autompg200K.csv"),use=1000)

def irrsled1(f="data/test4.csv",extra=showRows,
             initial=25,show1=True,show2=True,show3=True):
  random.seed(1)
  all = []
  for i,row in enumerate(rows(f)):
    if i == 0: 
      t= Table().ready(row,prep=float)
    else: 
      all.append(row)
  random.shuffle(all)
  print 'showtime..'
  a= AlienHunter()
  for i,row in enumerate(all):
    if  i<initial:
      t.put(row)
    elif  i == initial:
      t.put(row)
      tree = rrsl(t)
      a.reset()
      if show1: tree.show(extra=extra)
      tree.map(lambda x: a.put(x))
      print "before:",a.report()
      a.reset()
      tree.map(resetAllCounts)
      print 'nn-ing..'
    else:
      friends = tree.near(row).data
      if show2: print row,'==>\n\t',friends
  if show3: tree.show(extra=extra)
  tree.map(lambda x:a.put(x))
  print "after",a.report()

class AlienHunter():
  def __init__(o) : o.all=[]
  def put(o,d) : 
    if d.info : 
      print "pp", len(d.info.aliens)
      o.all.append(len(d.info.aliens))
  def report(o,p=20): 
    return map(lambda x: x,  #int(10000*x)/100,
               tiles(sorted(o.all),p))
  def reset(o) : o.all=[]

def resetAllCounts(o) :
   if not o.isLeaf(): o.info.resetCounts()

def irrsled2() : irrsled1(f="data/test3.csv",initial=20,
                          show1=False,show2=False,show3=False)

def irrsled3() : irrsled1(f="data/autompg.csv",initial=100,
                  show1=False,show2=False,show3=False)

def irrsled4() :
  irrsled1(f="data/autompg200K.csv",
           initial=1000,
           show1=False,show2=False,show3=False)

def irrsled5() :
  irrsled1(f="data/autompg25K.csv",
      initial=50,
      show2=False,show1=False,show3=False)
